package BluetoothFileMgr.start;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FileManager extends Activity {
	 
	
    static final ArrayList<String> dirs = new ArrayList<String>();
    static final ArrayList<String> type = new ArrayList<String>();
    static final ArrayList<Long> size = new ArrayList<Long>();
    static final ArrayList<String> items = new ArrayList<String>();//[] { "Default" };
    static ArrayAdapter<String> adapter2 = null;// = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dirs);
    BluetoothSocket fileSock = null;
    static TextView tv2 = null;
    public static Context fileManCon = null;
    DeviceConnect dc;
    //tv.setText("BLUETOOTH FILE MANAGER");
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.directory);
        //dirs.add("hello");
        tv2 = (TextView) findViewById(R.id.text2);
        tv2.setText("DIRECTORY:");
        ListView lv2 = (ListView) findViewById(R.id.mylist2);
        adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dirs);
        lv2.setAdapter(adapter2);
        final AlertDialog.Builder builder3 = new AlertDialog.Builder(this);
        final AlertDialog.Builder renameDialog = new AlertDialog.Builder(this);
        EditText input = new EditText(this);
        fileManCon = getApplicationContext();
    
        //if(BluetoothFileMgrActivity.mode.equals("Bluetooth"))
        //{
        	dc = new DeviceConnect(BluetoothFileMgrActivity.btDevice, BluetoothFileMgrActivity.adap, getApplicationContext()); 
            dc.read();
        //}
        //else
        //{
        //	dc = 
        //}
        
              
        lv2.setOnItemLongClickListener(new OnItemLongClickListener() {
        	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
        	{
        		final CharSequence[] options = {"Rename", "Move", "Delete", "Copy"};
            	builder3.setTitle(dirs.get(position)+" - Options");
            	final int pos = position;
            	builder3.setItems(options, new DialogInterface.OnClickListener() {
            	public void onClick(DialogInterface dialog, int option)
            	{	final EditText input = new EditText(getApplicationContext());
            		if(option==0)
            		{	
            			//EditText input = new EditText(getApplicationContext());
            			input.setText(dirs.get(pos));
            			input.setOnKeyListener(new OnKeyListener() {
            				public boolean onKey(View v, int keyCode, KeyEvent event)
            		        {
            					if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER))
            		            {
            						{	//String Name = input.getText().toString();
            		                   		/*Runnable writeThread4 = null;
            		                   		writeThread4 = new WriteThread("RENAME!!"+dirs.get(pos)+"!!"+Name);
            		                   		Thread wt4 = new Thread(writeThread4);
            		                   		wt4.start();*/
            		                   		//input.
            		                   		//dialog.dismiss();
            		                }
            		                return true;
            		            }
            		            return false;
            		        }
            			});
            				//renameDialog.setView(input);
            				//AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            			renameDialog.setTitle("Rename");
            			renameDialog.setMessage("Enter new name");
            			renameDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
             			   public void onClick(DialogInterface dialog, int which)
             			   {	String Name = input.getText().toString();        
             			   		Runnable writeThread4 = null;
             			   		writeThread4 = new WriteThread("RENAME!!"+dirs.get(pos)+"!!"+Name);
             			   		Thread wt4 = new Thread(writeThread4);
             			   		wt4.start();
             			   		dc.read();
             			   }
            			});
            			renameDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            			   public void onClick(DialogInterface dialog, int which)
            			   {	// do something when the user presses OK (place focus on weight input?)
            					  dialog.dismiss();   
            			   }
            			});
            			renameDialog.setView(input);
            			//alertDialog.setIcon(R.drawable.icon);
            			renameDialog.show();
            		}
            		else if(option==1)
            		{
            			Runnable writeThread2 = null;
     				    writeThread2 = new WriteThread("MOVE!!"+dirs.get(pos));
     				    Thread wt2 = new Thread(writeThread2);
     				    wt2.start();
     				    dc.read();
            		}
            		else if(option==2)
            		{
            			Runnable writeThread3 = null;
     				    writeThread3 = new WriteThread("DELETE!!"+dirs.get(pos));
     				    Thread wt3 = new Thread(writeThread3);
     				    wt3.start();
     				    dc.read();
            		}
            		else if(option==3)
            		{
            			//wt = new WriteThread("COPY!!"+dirs.get(pos));
            		}
            		//Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
            	}
            	});
            	AlertDialog alert = builder3.create();
            	alert.show();
        		/*final Dialog dialog = new Dialog(getApplicationContext());
    			dialog.setContentView(R.layout.custom);
    			dialog.setTitle("Title...");
     
    			// set the custom dialog components - text, image and button
    			TextView text = (TextView) dialog.findViewById(R.id.text);
    			text.setText("Android custom dialog example!");
    			ImageView image = (ImageView) dialog.findViewById(R.id.image);
    			image.setImageResource(R.drawable.ic_launcher);
     
    			Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);*/
    			// if button is clicked, close the custom dialog
    			/*dialogButton.setOnClickListener(new OnClickListener() {
    				@Override
    				public void onClick(View v, int id) {
    					dialog.dismiss();
    				}
    			});*/
        		return true;
        	}
    	});
        
        /*AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
        builder2.setMessage(R.string.dialog_text)
            .setCancelable(false)
            .setTitle("Options");
        //final AlertDialog btAlert = builder2.create();*/        
        
       	lv2.setOnItemClickListener(new OnItemClickListener() {
       		@Override
       		public void onItemClick(AdapterView<?> parent, View view, int position, long id)
       		{
       			Runnable writeThread = null;
       			if(type.get(position).equals("dir"))
       			{
       				writeThread = new WriteThread("GOTO!!"+dirs.get(position));
       				Thread t3 = new Thread(writeThread);
           			t3.start();
           			dc.read();
       			}
       			else
       			{
       				writeThread = new WriteThread("DOWNLOAD!!"+dirs.get(position));
       				Thread t3 = new Thread(writeThread);
           			t3.start();
           			dc.trial(dirs.get(position), size.get(position));
           			dc.read();
           			//tv2.setText("download expected");
           			           			    	         
       			}
       			//DataOutputStream out = null;
       			//byte[] b = dirs.get(position).getBytes();
    			try {
    				//out.writeUTF(dirs.get(position));
    				toastMessage("sent! "+dirs.get(position), Toast.LENGTH_SHORT);
    			} catch (Exception e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}
       		}
       	});

        
        
        Button exit2Button;
        exit2Button = (Button)findViewById(R.id.exit2);
        Button backButton;
        backButton = (Button)findViewById(R.id.back);
        Button addButton;
        addButton = (Button)findViewById(R.id.add);
        
        exit2Button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	//finish();
            	System.exit(0);
   
            }
           });
        
        backButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	Runnable writeThread = new WriteThread("BACK!!");
       			Thread t5 = new Thread(writeThread);
       			t5.start();
       			dc.read();
            	   }
           });
        
        addButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	//Intent myIntent = new Intent(v.getContext(), BluetoothFileMgrActivity.class);
                //startActivityForResult(myIntent, 0);
            	Runnable writeThread = new WriteThread("ADD!!"+"NF");
       			Thread t5 = new Thread(writeThread);
       			t5.start();
       			dc.read();
            	   }
           });
        
    }
    
    public void getFile() throws IOException
    {
    	DataInputStream fin = null;
		try {
			fin = new DataInputStream(fileSock.getInputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //int i = 0;
        //while(true)
        ///////////////////////////////////////////////////////////////
        {	DataOutputStream fout = null;
        	FileOutputStream f = new FileOutputStream(Environment.getExternalStorageDirectory().toString()+"/"+"yournewfile");
        	fout = new DataOutputStream(f);
        	//String st = sc.nextLine();
        	String st = null;
        	FileManager.tv2.setText("before readUTF");
        	st = fin.readUTF();
        	FileManager.tv2.setText("after readUTF n before writeUTF");
        	//if(!st.contains("!!"))
        	fout.writeUTF(st);
        	FileManager.tv2.setText("after writeUTF");
        	//FileManager.dirs.clear();
        	//FileManager.type.clear();
        }
    }
    
    
    Handler hand = new Handler()
    {  	public void handleMessage(Message msg)
    	{
      			//Toast toast = Toast.makeText(FileManager.fileManCon, (msg.obj).toString(), Toast.LENGTH_LONG);
    			//toast.show();
    			FileManager.tv2.setText((msg.obj).toString());
    			
       	}
    };
    
    public void trial(int position) //throws Exception
    {
    	
    	String filename = dirs.get(position);
    	DataInputStream din = DeviceConnect.din;
    	tv2.setText("inBeforeConn");
	    tv2.setText("inAftereConn");
	    
    	File newFile = null;
    	FileInputStream fin = null;
    	try {
    		//tv.setText("before");
    		newFile = new File(Environment.getExternalStorageDirectory().toString()+"/"+filename);
    		newFile.createNewFile();
    	} catch (Exception e) {
    		tv2.setText(e.toString());
    	}
    	
    	//DataInputStream dins = null;
    	//DataInputStream din = ConnectThread.din;;
    	//try {
			//dins = new DataInputStream(DeviceConnect.mmSocket.getInputStream());
		//} catch (IOException e1) {
			// TODO Auto-generated catch block
			//e1.printStackTrace();
		//}
    	//InputStream inst = null;
    	//try {
    	//	inst = DeviceConnect.mmSocket.getInputStream();
    	//} catch (IOException e){}
    	//int i = 0;
    	//while(true)
    	///////////////////////////////////////////////////////////////
    			
    		DataOutputStream dout = null;
    		FileOutputStream fout = null;
    		try {
    			fout = new FileOutputStream(newFile);
    			dout = new DataOutputStream(fout);
    			//fout.close();
    			
    		} catch (FileNotFoundException e) { } 	                   	
    		String st = null;
    		byte b[] = new byte[1000];
    		byte by;// = new byte();
    		//FileManager.tv2.setText("before readUTF");
    		try { 			
    			long i = 1;//pdf=246000
    			while(i<=2486)
    			{
    				//tv.setText(""+i);
    				b = new byte[1000];
    				din.read(b, 0, 1);
    				by = b[0];
    				dout.write(by);
    				i++;
    				tv2.setText("Read - "+i);
    			}
    			tv2.setText("readall");
    			//inst.close(); 
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			//tv.setText("catch of inst.read");
    		}
    	
    		try {
    			//fout.writeUTF(st);
    			//dout.write(b);
    			fout.close();
    			dout.close();
    		} catch (Exception e) { }//tv.setText("catch of dout.write"); }
    		  	
    }
    
    public void toastMessage(CharSequence text, int duration)
    {
    	Context context = getApplicationContext();
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
    
       
}